package com.unitechs.commons.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.*;
import java.util.Collection;

/**
 * 类工具
 * @author ZhouYz
 * @since 1.0.0
 */
@Slf4j
public final class ZyucObjectUtil {

    private ZyucObjectUtil(){
        //防止实例化
        throw new AssertionError();
    }

    /**
     * 将Java对象转换为JSON格式字符串
     * @param object 要转换的Java对象
     * @return JSON格式字符串
     * @throws JsonProcessingException 如果转换过程中出现异常
     */
    public static String zyucConvertObjectToJson(Object object) throws JsonProcessingException {
        return new ObjectMapper().writeValueAsString(object);
    }

    /**
     * 设置对象的空属性为null
     */
    public static void zyucSetEmptyFieldsToNull(Object object) {
        if (object == null) {
            return;
        }

        Class<?> clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            try {
                String fieldName = field.getName();
                Method getter = clazz.getMethod("get" + capitalize(fieldName));

                if (getter != null) {
                    Object propertyValue = getter.invoke(object);

                    if (isEmptyPropertyValue(propertyValue)) {
                        Method setter = clazz.getMethod("set" + capitalize(fieldName), field.getType());
                        setter.invoke(object, (Object) null);
                    }
                }
            } catch (Exception e) {
                log.info("处理属性时出现异常: {}", e.getMessage());
            }
        }
    }

    private static boolean isEmptyPropertyValue(Object propertyValue) {
        return (propertyValue instanceof String && ((String) propertyValue).trim().isEmpty())
                || (propertyValue instanceof Collection && ((Collection<?>) propertyValue).isEmpty())
                || (propertyValue != null && propertyValue.getClass().isArray() && ((Object[]) propertyValue).length == 0);
    }

    private static String capitalize(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }


}
